package ShuJu;

import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.io.*;
import GongJu.ExcelUtil;

/**
 * Excel数据访问基类
 * 提供通用的Excel文件读写操作
 */
public abstract class ExcelDao<T> {
    protected static final String EXCEL_PATH = "data/shopping_system.xlsx";
    protected static Workbook workbook;
    protected final String sheetName; // 工作表名称
    
    protected ExcelDao(String sheetName) {
        this.sheetName = sheetName;
        if (workbook == null) {
            initWorkbook();
        }
    }
    
    /**
     * 初始化工作簿
     */
    private void initWorkbook() {
        File file = new File(EXCEL_PATH);
        if (file.exists()) {
            try (FileInputStream fis = new FileInputStream(file)) {
                workbook = WorkbookFactory.create(fis);
            } catch (IOException e) {
                e.printStackTrace();
                workbook = WorkbookFactory.create(true);
            }
        } else {
            workbook = WorkbookFactory.create(true);
        }
    }
    
    // 基础的CRUD操作
    public abstract List<T> chaXunSuoYou();                  // 查询所有记录
    public abstract T chaXunByBiaoShi(String biaoShi);      // 根据标识查询
    public abstract boolean xinZeng(T shuju);               // 新增记录
    public abstract boolean xiuGai(T shuju);               // 修改记录
    public abstract boolean shanChu(String biaoShi);       // 删除记录
    
    /**
     * 获取工作表
     */
    protected Sheet getSheet() {
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workbook.createSheet(sheetName);
        }
        return sheet;
    }
    
    /**
     * 保存工作簿
     */
    protected void baoCunWenJian() {
        try (FileOutputStream fos = new FileOutputStream(EXCEL_PATH)) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 